package com.java.pay.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.common.vo.R;
import com.java.pay.entity.PaymentInfo;
import com.java.pay.mapper.PaymentInfoMapper;
import com.java.pay.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangli
 * @since 2019-12-15
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
	@Autowired
	private PaymentInfoMapper paymentInfoMapper;
	@Autowired
	private StringRedisTemplate redisTemplate;

	public static final String PAY_TOKEN = "pay_token_";

	@Override
	public R addPaymentInfo(@RequestBody PaymentInfo paymentInfo) {
		paymentInfoMapper.insert(paymentInfo);
		Long paymentInfoId = paymentInfo.getId();
		if (paymentInfoId == null) {
			return R.error("系统错误,未获取到支付id");
		}
		String token = RandomUtil.randomString(32);
		redisTemplate.opsForValue().set(PAY_TOKEN + token, String.valueOf(paymentInfoId), 2, TimeUnit.HOURS);
		return R.ok(token);
	}

	@Override
	public ResponseEntity<PaymentInfo> getPayInfoByToken(@RequestParam("token") String token) {
		if (StrUtil.isEmpty(token)) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
		}
		String payInfoId = redisTemplate.opsForValue().get(PAY_TOKEN + token);
		if (StrUtil.isEmpty(payInfoId)) {
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
		}
		PaymentInfo paymentInfo = paymentInfoMapper.selectById(Long.parseLong(payInfoId));
		return ResponseEntity.ok(paymentInfo);
	}

	@Override
	public ResponseEntity<PaymentInfo> getPayInfoByOrderId(@RequestParam("orderId") String orderId) {
		PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderId, orderId));
		if (paymentInfo == null) {
			return ResponseEntity.badRequest().build();
		}
		return ResponseEntity.ok(paymentInfo);
	}

	@Override
	public R updatePayInfo(PaymentInfo paymentInfo) {
		paymentInfoMapper.updateById(paymentInfo);
		return R.ok();
	}

}
